package com.fkdx.webman.service;

import com.fkdx.common.constant.CardType;
import com.fkdx.common.enums.sys.GroupException;
import com.fkdx.dao.entity.Voucher;
import com.fkdx.service.VoucherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 提卡
 *
 * @author : yl
 * @date : 2024-11-24
 */

@Slf4j
@Service
public class CardNumService {


    @Resource
    private VoucherService voucherService;
    /**
     * 异步调用python
     */
    @Async
    public void getCardNum(String url, Integer count, Long id, Integer type, Integer totalValue) {
        // DIGI的场合
        if (type == 4 || type == 5 || type == 6) {
            log.info("执行DIGI:{}", id);
            Voucher v = voucherService.sysVoucher(id);
            if (v != null && v.getNum() == null) {
                String[] command = {"python", "C:\\workspace\\python-code\\CookieDigi.py", url, String.valueOf(id), String.valueOf(v.getId())};
                send(command);
            }
        } else {
            String pythonFile = getPythonFile(type);
            String[] command = {"python", pythonFile, url, String.valueOf(count), String.valueOf(id), String.valueOf(totalValue)};
            send(command);
        }
    }

    /**
     * 推送请求
     * @param command 请求文件及参数
     */
    private void send(String[] command) {
        try {
            ProcessBuilder pb = new ProcessBuilder(command);
            Process process = pb.start();
            process.waitFor();
        } catch (Exception e) {
            log.error("调用异常；【{}】", e.getMessage(), e);
            throw new GroupException(e.getMessage());
        }
    }

    /**
     * 根据类型py文件
     * @param type 类型
     * @return py文件
     */
    private String getPythonFile(int type) {
        // 指定文件路径
        String pythonFile = "C:\\workspace\\python-code\\";
        switch (type) {
            case CardType.G4B_AMAZON:
                pythonFile = pythonFile + "G4bAmazon.py";
                break;
            case CardType.G4B_APPLE:
                pythonFile = pythonFile + "G4bApple.py";
                break;
            case CardType.G4B_GOOGLE:
                pythonFile = pythonFile + "G4bGoogle.py";
                break;
            case CardType.DIGI_AMAZON:
                pythonFile = pythonFile + "DigiAmazon.py";
                break;
            case CardType.DIGI_APPLE:
                pythonFile = pythonFile + "DigiApple.py";
                break;
            case CardType.DIGI_GOOGLE:
                pythonFile = pythonFile + "DigiGoogle.py";
                break;
        }
        return pythonFile;
    }
}
